package com.pks.autoInsurance.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.pks.autoInsurance.dto.CustomerDto;

/**
 * Implementation class for LoginDAO
 * 
 * @author Pankaj Soni
 * 
 */
public class LoginDAOImpl extends AutoInsuranceDAO implements LoginDAO {

	private static final Logger LOGGER = Logger.getLogger(LoginDAOImpl.class);

	/**
	 * 
	 * @see com.cts.autoInsurance.dao.LoginDAO#authenticateUser(com.cts.autoInsurance
	 *      .dto.RegistrationDtoReq)
	 */
	@Override
	public final int authenticateUser(final CustomerDto customer) {
		LOGGER.debug("begin");
		final Connection connection = this.getConnection();
		final String sql = "SELECT SSN,PASSWD FROM REGISTRATION WHERE SSN=? AND PASSWD=?";
		LOGGER.info("sql: " + sql);
		try {
			connection.setAutoCommit(false);
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			preparedStatement.setString(1, customer.getSsn());
			preparedStatement.setString(2, customer.getPasswd());
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				if (resultSet.getString("SSN").equalsIgnoreCase("adminadmin")) {
					return VALID_ADMIN;
				}
				return VALID_USER;
			}
		} catch (SQLException e) {
			LOGGER.error(e.getMessage());
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				LOGGER.error(e.getMessage());
			}
		}
		return INVALID_USER;
	}
}
